<template>
  <div>
    <h2>菜品管理</h2>
    <a-button class="add-btn" type="primary" @click="addDish"
      >新增菜品</a-button
    >
    <a-input-search
      v-model:value="search_name"
      placeholder="搜索菜品"
      style="width: 200px"
      @search="search"
    />
    <!-- <a-table :dataSource="dishes" :columns="columns" rowKey="id"> -->
    <a-table :dataSource="foods_list" :columns="columns" rowKey="id">
      <template #cate="{ record }">
        <text v-for="it in record.categories" :key="it">{{ it }}、</text>
      </template>
      <template #action="{ record }">
        <a-button @click="editDish(record)">修改</a-button>
        <a-button type="primary" @click="deleteDish(record.food_id)" danger
          >删除</a-button
        >
        <!-- <text v-if="column.dataIndex == 'on_sale'">abc</text> -->
      </template>
    </a-table>
    <!-- 模态对话框 -->
    <a-modal v-model:open="open_edit" title="修改" @ok="handleEdit" @cancel="handelCancel">
      <div v-for="(item, key) in tmp_edit_item" v-bind:key="key">
        <text>{{ key }}</text>
        <a-input v-model:value="tmp_edit_item[key]" placeholder="请输入内容" />
      </div>

      <!-- <a-button @click="addImg(record)">添加图片</a-button> -->

      <!-- 限制最大待上传的文件数量为 1 -->
      <!-- 添加选择文件后的回调和移除待上传文件的回调 -->
      <a-upload
        :before-upload="beforeUpload"
        :max-count="1"
        @remove="handleRemove"
      >
        <a-button>
          <upload-outlined></upload-outlined>
          选择图片
        </a-button>
      </a-upload>
      <!-- 点击上传按钮 -->
      <a-button @click="triggerUpload" :loading="btnLoading">上传</a-button>

    </a-modal>
    <a-modal v-model:open="open_add" title="新增" @ok="handleAdd" @cancel="handelCancel">
      <div v-for="(item, key) in tmp_edit_item" v-bind:key="key">
        <text>{{ key }}</text>
        <a-input v-model:value="tmp_edit_item[key]" placeholder="请输入内容" />
      </div>
      <!-- <a-button @click="addImg(record)">添加图片</a-button> -->

      <!-- 限制最大待上传的文件数量为 1 -->
      <!-- 添加选择文件后的回调和移除待上传文件的回调 -->
      <a-upload
        :before-upload="beforeUpload"
        :max-count="1"
        @remove="handleRemove"
      >
        <a-button>
          <upload-outlined></upload-outlined>
          选择图片
        </a-button>
      </a-upload>
      <!-- 点击上传按钮 -->
      <a-button @click="triggerUpload" :loading="btnLoading">上传</a-button>

    </a-modal>
  </div>
</template>

<script>
import axios from "axios";
import Qs from "qs";
import { UploadOutlined } from "@ant-design/icons-vue";
// import fruitApi from "@/api/fruitApi";
import { ref } from "vue";
import { Upload } from "ant-design-vue";
// import {Notice} from "@/utils/interfaces";


export default {
  data() {
    return {
      dish: {},
      search_name: "",
      fileList: [],
      base64img: {},
      btnLoading: false,
      tmp_edit_item_bak: {},
      all_categories: [],
      shop_id: 0, // TODO: 这里先写死为1
      open_edit: false,
      open_add: false,
      tmp_edit_item: {},
      which_click: 0,
      foods_list: [],
      categories: [],
      dishes: [
        { id: 1, name: "红烧肉", price: 15 },
        { id: 2, name: "宫保鸡丁", price: 12 },
      ],
      columns: [
        { title: "菜品名称", dataIndex: "name", key: "name" },
        { title: "价格", dataIndex: "price", key: "price", width: 100 },
        // { title: '分类', dataIndex: 'categories', key: 'categories' },
        {
          title: "分类",
          key: "categories",
          slots: { customRender: "cate" },
          ellipsis: true,
        },
        {
          title: "描述",
          dataIndex: "description",
          key: "description",
          ellipsis: true,
        },
        { title: "折扣", dataIndex: "discount", key: "discount", width: 100 },
        {
          title: "图片url",
          dataIndex: "img_url",
          key: "image",
          ellipsis: true,
        },
        { title: "是否上架", dataIndex: "on_sale", key: "on_sale", width: 100 },
        { title: "操作", key: "action", slots: { customRender: "action" } },
      ],
      //   post_val: {},
      food_id: 0,
    };
  },
  mounted: function () {
    // 判断是否登录
    if (!this.$store.state.is_login)
    {
        alert("未登录，请先登录!")
       this.$router.push('/');
       return;
    }

    // 获取商店id
    this.shop_id = this.$store.state.shop_id;
    

    // 请求获取食品信息
    axios
      .get("/shop/getMenuByShopId", {
        params: {
          shop_id: this.shop_id,
        },
      })
      .then((res) => {
        this.foods_list = res.data;
        console.log(this.foods_list);
      });
  },
  methods: {
    eng2Chi(item) {
      let tmp = {};
      for (let index in item) {
        if (index == "categories") {
          // console.log('tmpp is: ', tmp);
          tmp["分类"] = item[index];
          continue;
        }
        if (index == "description") {
          tmp["描述"] = item[index];
          continue;
        }
        if (index == "discount") {
          tmp["折扣"] = item[index];
          // dish[index] = 121212;
          continue;
        }
        if (index == "on_sale") {
          tmp["是否上架"] = item[index];
          continue;
        }
        if (index == "price") {
          tmp["价格"] = item[index];
          continue;
        }
        if (index == "name") {
          tmp["菜品名称"] = item[index];
          continue;
        }
        if (index == "img_url") {
          tmp["图片url"] = item[index];
          continue;
        }
      }

      return tmp;
    },

    chi2Eng(item) {
      let tmp = {};
      for (let index in item) {
        if (index == "分类") {
          // console.log('tmpp is: ', tmp);
          tmp["categories"] = item[index];
          continue;
        }
        if (index == "描述") {
          tmp["description"] = item[index];
          continue;
        }
        if (index == "折扣") {
          tmp["discount"] = item[index];
          continue;
        }
        if (index == "是否上架") {
          tmp["on_sale"] = item[index];
          continue;
        }
        if (index == "价格") {
          tmp["price"] = item[index];
          continue;
        }
        if (index == "菜品名称") {
          tmp["name"] = item[index];
          continue;
        }
        if (index == "图片url") {
          tmp["img_url"] = item[index];
          continue;
        }
      }

      return tmp;
    },
    addDish() {
      // 跳转到新增菜品页面或弹出对话框
      this.open_add = true;
      console.log("新增菜品");
      let tmp = {
        name: "",
        price: 0,
        categories: [],
        description: "",
        discount: 0,
        on_sale: 1,
        img_url: "",
      };

      tmp = this.eng2Chi(tmp);
      this.tmp_edit_item = { ...tmp };
    },
    handleAdd() {
      let post_val = { ...this.tmp_edit_item };
      post_val = this.chi2Eng(post_val);
      let tmp_str = post_val["categories"];
      console.log('tmp_str: ', tmp_str)
      let tmp_list = []
      if (tmp_str.indexOf(",") != -1)
      {
        tmp_list = tmp_str.split(",");
      }
      else
      {
        tmp_list.push(tmp_str);
      }
      // for (let i = 0; i < tmp_list.length; i++) //TODO: 这里需要转换一下，因为后端需要，但是有bug，转换之后是空值
      // {
        // tmp_list[i] = toString(tmp_list[i]);
      // }
      // if (this.img_append != '')
      // {
      //   post_val["img_url"] = this.img_append;
      //   this.img_append = '';
      // }
      console.log("tmp_list: ", tmp_list);
      post_val["categories"] = tmp_list;
      console.log("post_val: ", post_val);
      post_val["need_parse"] = 1;
      post_val["shop_id"] = this.shop_id;

      console.log("add post_val: ", post_val);
      let obj = Qs.stringify(post_val);
      console.log("add obj: ", obj);

      // 向后端请求修改菜品信息
      axios
        .post("/shop/addFoodByShopId", obj, {
          headers: { "Content-Type": "application/x-www-form-urlencoded" },
        })
        .then((res) => {
          this.open_add = false;
          console.log("res: ", res);
          if (res.data.msg == "success")
          {
            post_val["food_id"] = res.data.food_id;
            this.foods_list.push(post_val);
            this.fileList = null;
            alert("添加成功!");
          }
          else
          {
            alert("添加失败!")
          }
        });
    },
    editDish(dish) {
      // 跳转到修改菜品页面或弹出对话框
      this.open_edit = true;
      //将当前dish对象赋值给edit_dish
      let tmp = {};
      // this.dish = dish;
      console.log("dish: ", dish);
      tmp = this.eng2Chi(dish);
      // 做个备份
      this.tmp_edit_item_bak = {...tmp};

      this.tmp_edit_item = { ...tmp };

      console.log("修改菜品:", this.tmp_edit_item);
      this.food_id = dish.food_id;
    },

    handleEdit() {
      console.log("tmp_edit_item: ", this.tmp_edit_item);

      //转换回来
      let post_val = {};
      post_val = this.chi2Eng(this.tmp_edit_item);
      post_val["food_id"] = this.food_id;
      post_val["need_parse"] = 1;
      // if (this.img_append != '')
      // {
      //   post_val["img_url"] = this.img_append;
      //   this.img_append = '';
      // }
      console.log("edit post_val: ", post_val);
      let obj = Qs.stringify(post_val);
      console.log("edit obj: ", obj);

      // 向后端请求修改菜品信息
      axios
        .post("/shop/modiFoodByFoodId2", obj, {
          headers: { "Content-Type": "application/x-www-form-urlencoded" },
        })
        .then((res) => {
          this.open_edit = false;
          console.log("res: ", res);
          if (res.data.msg == "success")
          {
            for (let i=0; i<this.foods_list.length; i++)
            {
              if (this.foods_list[i].food_id == this.food_id)
              {
                this.foods_list[i] = post_val;
                break;
              }
            }
            this.fileList = null;
            alert("修改成功！");
          }
          else
          {
            alert("修改失败！");
          }
        });

      // https.post()
    },
    deleteDish(id) {
      // 调用API删除菜品
      console.log("删除菜品:", id);

      let post_val = {};
      post_val["food_id"] = id;
      post_val["need_parse"] = 1;
      let obj = Qs.stringify(post_val);
      console.log("del obj:", obj)
      axios
        .post("/shop/delFoodByFoodId2", obj, {
          headers: { "Content-Type": "application/x-www-form-urlencoded" },
        })
        .then((res) => {
          console.log("res: ", res);
          for (let i=0; i<this.foods_list.length; i++)
          {
            if ( this.foods_list[i].food_id == id)
            {
              console.log("del food: ", this.foods_list[i]);
              this.foods_list.splice(i, 1);
            }
          }
          alert("删除成功");
        });
    },

    // // 添加图片
    // addImg(){
    //   // 向资源服务器请求新增图片的url，然后增加到图片url框中

    // }
    getBase64(img, callback) {
      const reader = new FileReader(img, callback);
      reader.addEventListener("load", () => callback(reader.result));
      // ↑ 监听 reader 的 load 事件，触发时执行回调函数
      // 回调函数的作用就是将图片编码的base64字符串传给 base64img
      reader.readAsDataURL(img);
    },

    beforeUpload(file) {
      console.log(file);
      // 判断文件是否为图片格式
      const isImg = file.type === "image/jpeg" || file.type === "image/png";

      // 如果文件不是图片格式则禁止上传
      if (!isImg) {
        // Notice.error("只能上传 jpeg/jpg/png 格式的文件！");
        // ↑ Notice.error 是我自己写的 Notice 类的一个静态函数
        // 用的是 antdv 的 Notifiacation
        return Upload.LIST_IGNORE;
      }
      this.fileList = file;
      // ↓ 获取所需要上传图片的 Base64 编码
      this.getBase64(this.fileList, (cb_img) => {
        // 将获取到的所要上传图片的 Base64 编码渲染到图片上
        this.base64img = cb_img;
      });
      return false;
    },

    triggerUpload() {
      const formData = new FormData();

      // 对文件列表 判空
      if (this.fileList != null) {
        formData.append("image", this.fileList);
        // console.log("formData: ", formData);
      } else {
        // Notice.error("文件不能为空！")
        return Upload.LIST_IGNORE;
      }

      // formData["need_parse"] = 1;
      // let obj = Qs.stringify(formData);
      // ↓ 在上传过程中，按钮为 loading 状态
      this.btnLoading = true;

      axios
        .post("/shop/uploadImg", formData, {
          baseURL: "http://localhost:8082",
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          // ↓ 上传成功，按钮为默认状态
          this.btnLoading = false;
          // ↓ 获取上传成功后的图片 url
          const imgUrl = res.data.data.url;
          // ↓ 将获取到的图片 url 赋值给 imgUrl
          console.log("imgUrl: ", imgUrl);
          // 先备份，然后将tmp_edit_item中的img_url字段设置为imgUrl
          this.img_append = imgUrl;
          this.tmp_edit_item['图片url'] = imgUrl;
          alert("上传成功");
        });
    },

    handleRemove() {
      this.fileList = null;
      // ↑ 置空待上传文件列表
      this.base64img = null;
    },

    // changeUploadItemColor(color){
    //   const uploadListItem = document.querySelector(".ant-upload-list-item-name");
    //   // ↑ 类名是 antdv 规定的，选择这个类名即可
    //   (uploadListItem).style.color = color;
    //   // ↑ 使item文字变色
    // }

    search()
    {
      axios.get('/shop/getFoodByName', {
        params: {
          shop_id: this.shop_id,
          name: this.search_name,
        }
      }).then((res)=>{
        this.foods_list = res.data;
        console.log(this.foods_list);
      });
    },

    handelCancel()
    {
      console.log("cancel");
      this.open_add = false;
      this.open_edit = false;
      this.fileList = null;
      console.log("tmp_edit_item: ", this.tmp_edit_item);
      console.log("tmp_edit_item_bak: ", this.tmp_edit_item_bak);
      this.tmp_edit_item = { ...this.tmp_edit_item_bak };
    }
  },


};
</script>

<style scoped>
/* 自定义样式 */
h2 {
  margin-bottom: 16px;
}
.add-btn {
  margin-left: 1200px;
}
</style>